﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using RiskMan.Config;
using RiskMan.DataClass.Models;
using RiskMan.DataClass.Models.Quik;
using RiskMan.DataClass.Models.RM;
using RiskMan.Models;
using System.Diagnostics;

namespace RiskMan.Views.Stop
{
    /// <summary>
    /// Обработка, Очистка стопов
    /// </summary>
    class StopsClass
    {
        private PositionModel positionModel;
        private MainWindow mainWindow;
        private PositionModel _pM;
        private string _formate;

        #region Конструкторы

        /// <summary>
        /// конструктор для Remove()
        /// </summary>
        /// <param name="seccode"></param>
        /// <param name="mianWindow"></param>
        public StopsClass(PositionModel pm, MainWindow mianWindow)
        {
            this._pM = pm;
            this.mainWindow = mianWindow;
        }

        /// <summary>
        /// конструктор для Start()
        /// </summary>
        /// <param name="positionModel"></param>
        /// <param name="mainWindow"></param>
        /// <param name="_formate"></param>
        public StopsClass(PositionModel positionModel, MainWindow mainWindow, string _formate)
        {
            this.positionModel = positionModel;
            this.mainWindow = mainWindow;
            this._formate = _formate;
        }

        #endregion

        /// <summary>
        /// Начало обработки Стопов по текущей позиции positionModel
        /// </summary>
        public void Start()
        {
            // поиск массива стопов по текущему Коду Бумаги
            List<StopListModel> stoplist = this.GetStops(positionModel);
            DealModel deal = this.Search(
                mainWindow._dataProvider.DealList,
                mainWindow._dataProvider.DealSOrderList);

            for (int i = 0; i < stoplist.Count; i++)
            {
                if (RiskManBlockByClient(stoplist[i].ClientCode, stoplist[i].Account) == true)
                {
                    stoplist[i].CurrentPos = mainWindow._dataProvider.GetCurPosition(stoplist[i].Seccode, stoplist[i].Account, stoplist[i].ClientCode);
                    stoplist[i].CurrentPrice = deal.Price;

                    this.Load();
                    mainWindow._dataProvider.StopLossOrderList = mainWindow._dataProvider.StopLossOrderList.Where(a => a.Result != cfg.Cancel).ToList();

                    mainWindow._dataProvider.TakeOrderList = mainWindow._dataProvider.TakeOrderList.Where(a => a.Status != cfg.Cancel).ToList();
                    var DealList = mainWindow._dataProvider.DealList.Where(a => a.Seccode == positionModel.Seccode).
                            Where(a => a.Account == positionModel.Account).
                            Where(a => a.ClientCode == positionModel.ClientCode).ToList();

                    var list = mainWindow._dataProvider.StopLossOrderList.Where(a => a.Seccode == positionModel.Seccode).
                            Where(a => a.TradeAccount == positionModel.Account).
                            Where(a => a.ClientCode == positionModel.ClientCode).ToList();

                    if (list.Count > stoplist.Count)
                    {
                        for (int i_SL = 0; i_SL < list.Count - 1; i_SL++)
                        {
                            // if (!mainWindow._dataProvider.StopLossOrderList.Contains(list[i_SL]) && i_SL < list.Count - 1)
                            mainWindow._dataProvider.StopLossOrderList.Remove(list[i_SL]);
                            list.Remove(list[i_SL]);
                            i_SL--;
                        }
                    }

                    #region STOP_LIMIT

                    if (stoplist[i].TypeStop == cfg.StopLimit)
                    {
                        SPrice sprice;
                        if (DealList.Count != 0)
                        {
                            if (deal.Price != 0)
                            {
                                stoplist[i].PriceDeal = deal.Price;
                                stoplist[i].ClassCode = deal.ClassCode;
                                sprice = SPrice.GetStopLimitePrices
                                (
                                    stoplist[i],
                                    deal,
                                    mainWindow._dataProvider.GetAccuraccy(positionModel.Seccode)
                                );

                                if (IsSend(list.Where(a => a.TypeStop == cfg.StopLimit).ToList(), sprice) == true)
                                {
                                    SendStop(getOperation(deal), sprice.Stopprice, sprice.Price, Math.Abs(positionModel.Count), deal);
                                }
                            }
                            else
                            {
                                sprice = SPrice.GetStopLimitePrices
                                (
                                    stoplist[i],
                                    stoplist[i].PriceDeal,
                                    mainWindow._dataProvider.GetAccuraccy(positionModel.Seccode),
                                    (positionModel.Count < 0 ? cfg.Buy : cfg.Sell),
                                    positionModel.Seccode
                                );
                                if (IsSend(list.Where(a => a.TypeStop == cfg.StopLimit).ToList(), sprice) == true)
                                {
                                    SendStop((positionModel.Count < 0 ? 'B' : 'S'), sprice.Stopprice, sprice.Price, Math.Abs(positionModel.Count),
                                        stoplist[i].Seccode, stoplist[i].ClassCode, stoplist[i].Account, stoplist[i].ClientCode);
                                }
                            }
                        }
                        else
                        {
                            stoplist[i].CurrentPrice = stoplist[i].PriceDeal;
                            //если подключение клиента к РМ произошло когда у клиента уже были позиции и нет данных в таблицах по ценам приобретения
                            if (stoplist[i].PriceDeal == 0)
                            {
                                stoplist[i].PriceDeal = mainWindow._dataProvider.GetLastPrice(stoplist[i].Seccode);
                            }
                            sprice = SPrice.GetStopLimitePrices
                            (
                                stoplist[i],
                                stoplist[i].PriceDeal,
                                mainWindow._dataProvider.GetAccuraccy(positionModel.Seccode),
                                (positionModel.Count < 0 ? cfg.Buy : cfg.Sell),
                                positionModel.Seccode
                            );

                            if (IsSend(list.Where(a => a.TypeStop == cfg.StopLimit).ToList(), sprice) == true)
                            {
                                if (stoplist[i].ClassCode == null)
                                {
                                    mainWindow._dataProvider.GetClasscode(stoplist[i].Seccode);
                                }
                                SendStop((positionModel.Count < 0 ? 'B' : 'S'), sprice.Stopprice, sprice.Price, Math.Abs(positionModel.Count),
                                   stoplist[i].Seccode, stoplist[i].ClassCode, stoplist[i].Account, stoplist[i].ClientCode);
                            }
                        }
                    }

                    #endregion

                    #region TAKE_PROFIT

                    if (stoplist[i].TypeStop == cfg.TakeProfit)
                    {
                        SPrice sprice;
                        if (DealList.Count != 0)
                        {
                            stoplist[i].PriceDeal = deal.Price;
                            stoplist[i].ClassCode = deal.ClassCode;
                            sprice = SPrice.GetTakeProfitPrices(stoplist[i], deal, mainWindow._dataProvider.GetAccuraccy(positionModel.Seccode));
                        }
                        else
                        {
                            sprice = SPrice.GetTakeProfitPrices
                            (
                            stoplist[i],
                            stoplist[i].PriceDeal,
                            mainWindow._dataProvider.GetAccuraccy(positionModel.Seccode),
                            (positionModel.Count < 0 ? cfg.Buy : cfg.Sell),
                            positionModel.Seccode
                            );
                        }
                        if (IsSend(stoplist[i], list.Where(a => a.TypeStop == cfg.TakeProfit).ToList(), sprice) == true)
                        {
                            SendTake(getOperation(deal), sprice.Stopprice, Math.Abs(positionModel.Count), deal, stoplist[i].TakeOtst, stoplist[i].TakeSprd, this.GetTypeR(stoplist[i].TypeRasch));
                        }
                    }

                    #endregion

                    #region STOP_TAKE_ORDER

                    if (stoplist[i].TypeStop == cfg.StopTakeOrder)
                    {
                        #region take_price
                        SPrice take_sprice;
                        if (DealList.Count != 0)
                        {
                            stoplist[i].PriceDeal = deal.Price;
                            stoplist[i].ClassCode = deal.ClassCode;
                            take_sprice = SPrice.GetTakeProfitPrices
                            (
                                stoplist[i],
                                deal,
                                mainWindow._dataProvider.GetAccuraccy(positionModel.Seccode)
                            );
                        }
                        else
                        {
                            take_sprice = SPrice.GetTakeProfitPrices
                            (
                            stoplist[i],
                            stoplist[i].PriceDeal,
                            mainWindow._dataProvider.GetAccuraccy(positionModel.Seccode),
                            (positionModel.Count < 0 ? cfg.Buy : cfg.Sell),
                            positionModel.Seccode
                            );
                        }
                        #endregion

                        #region stop_price
                        SPrice stop_sprice;
                        if (DealList.Count != 0)
                        {
                            stoplist[i].PriceDeal = deal.Price;
                            stop_sprice = SPrice.GetStopLimitePrices
                            (
                                stoplist[i],
                                deal,
                                mainWindow._dataProvider.GetAccuraccy(positionModel.Seccode)
                            );
                        }
                        else
                        {
                            stop_sprice = SPrice.GetStopLimitePrices
                            (
                                stoplist[i],
                                stoplist[i].PriceDeal,
                                mainWindow._dataProvider.GetAccuraccy(positionModel.Seccode),
                                (positionModel.Count < 0 ? cfg.Buy : cfg.Sell),
                                positionModel.Seccode
                            );
                        }
                        #endregion

                        if (IsSend(stoplist[i], list.Where(a => a.TypeStop == cfg.StopTakeOrder).ToList(), take_sprice, stop_sprice) == true)
                        {
                            SendStopTake(getOperation(deal), deal, Math.Abs(positionModel.Count), stop_sprice.Price, take_sprice.Stopprice,
                                stoplist[i].TakeOtst, this.GetTypeR(stoplist[i].TypeRasch), stoplist[i].TakeSprd, "NO", stop_sprice.Stopprice);
                        }
                    }

                    #endregion

                    #region LINKED_ORDER

                    if (stoplist[i].TypeStop == cfg.LinkedOrder)
                    {
                        SPrice sprice;
                        if (DealList.Count != 0)
                        {
                            stoplist[i].PriceDeal = deal.Price;
                            stoplist[i].ClassCode = deal.ClassCode;
                            sprice = SPrice.GetStopLimitePrices
                            (
                                stoplist[i],
                                deal,
                                mainWindow._dataProvider.GetAccuraccy(positionModel.Seccode)
                            );
                        }
                        else
                        {
                            sprice = SPrice.GetStopLimitePrices
                            (
                                stoplist[i],
                                stoplist[i].PriceDeal,
                                mainWindow._dataProvider.GetAccuraccy(positionModel.Seccode),
                                (positionModel.Count < 0 ? cfg.Buy : cfg.Sell),
                                positionModel.Seccode
                            );
                        }

                        SPrice tprice;
                        if (DealList.Count != 0)
                        {
                            tprice = SPrice.GetLinkedOrderPrices(
                            stoplist[i],
                            deal,
                            mainWindow._dataProvider.GetAccuraccy(positionModel.Seccode)
                        );
                        }
                        else
                        {
                            tprice = SPrice.GetLinkedOrderPrices(
                                stoplist[i],
                                stoplist[i].PriceDeal,
                                mainWindow._dataProvider.GetAccuraccy(positionModel.Seccode),
                                (positionModel.Count < 0 ? cfg.Buy : cfg.Sell),
                                positionModel.Seccode
                            );
                        }

                        if (IsSendLinked(stoplist[i], list.Where(a => a.TypeStop == cfg.LinkedOOrder).ToList(), sprice, tprice) == true)
                        {
                            SendLinkedStop(getOperation(deal), sprice, tprice, Math.Abs(positionModel.Count), deal);
                        }
                    }

                    #endregion

                    #region TAKE_PROFIT_LINKED_ORDER

                    if (stoplist[i].TypeStop == cfg.TakeProfitLimitOrder)
                    {
                        SPrice sprice;
                        if (DealList.Count != 0)
                        {
                            stoplist[i].PriceDeal = deal.Price;
                            stoplist[i].ClassCode = deal.ClassCode;
                            sprice = SPrice.GetTakeProfitPrices(stoplist[i], deal, mainWindow._dataProvider.GetAccuraccy(positionModel.Seccode));
                        }
                        else
                        {
                            sprice = SPrice.GetTakeProfitPrices
                           (
                           stoplist[i],
                           stoplist[i].PriceDeal,
                           mainWindow._dataProvider.GetAccuraccy(positionModel.Seccode),
                           (positionModel.Count < 0 ? cfg.Buy : cfg.Sell),
                           positionModel.Seccode
                           );
                        }
                        if (IsSendTakeLimit(stoplist[i],
                            mainWindow._dataProvider.TakeOrderList.
                                            Where(a => a.Seccode == positionModel.Seccode).
                                            Where(a => a.Account == positionModel.Account).
                                            Where(a => a.ClientCode == positionModel.ClientCode).ToList(),
                                      sprice) == true)
                        {
                            this.SendOrder(getOperation(deal), sprice.Stopprice, Math.Abs(positionModel.Count), deal, stoplist[i].TakeOtst, stoplist[i].TakeSprd, this.GetTypeR(stoplist[i].TypeRasch));
                        }
                    }


                    #endregion
                }
                else
                    stoplist[i].IsStart = false;
            }
        }

        private bool RiskManBlockByClient(string clientcode, string account)
        {
            try
            {
                for (int i = 0; i < mainWindow._dataProvider.ACLimiteItems.Count; i++)
                {
                    if (mainWindow._dataProvider.ACLimiteItems[i].Account == account &&
                         mainWindow._dataProvider.ACLimiteItems[i].ClientCode == clientcode &&
                         mainWindow._dataProvider.ACLimiteItems[i].NextLevel != 0)
                    {
                        for (int j = 0; j < mainWindow._dataProvider.RMItems.Count; j++)
                        {
                            if (mainWindow._dataProvider.RMItems[j].Account == account &&
                                 mainWindow._dataProvider.RMItems[j].ClientCode == clientcode &&
                                mainWindow._dataProvider.RMItems[j].isRun == true
                               )
                            {
                                if (1 == mainWindow._dataProvider.ACLimiteItems[i].NextLevel)
                                    return false;
                                else
                                    return true;
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                return true;
            }
            return true;
        }

        /// <summary>
        /// начало обработки стопов если текущая позиция positionModel равна 0
        /// </summary>
        public void Remove()
        {

            // Удаление сделок по коду бамаги            
            List<DealModel> res_Deal = new List<DealModel>();
            for (int i = 0; i < mainWindow._dataProvider.DealSOrderList.Count; i++)
            {
                if (mainWindow._dataProvider.DealSOrderList[i].Seccode != _pM.Seccode &&
                    mainWindow._dataProvider.DealSOrderList[i].Account != _pM.Account &&
                    mainWindow._dataProvider.DealSOrderList[i].ClientCode != _pM.Account)
                    res_Deal.Add(mainWindow._dataProvider.DealSOrderList[i]);
            }
            //снятие ордеров и стопов при нулевой позиции
            for (int j = 0; j < mainWindow._dataProvider.OrderList.Count; j++)
            {
                if (mainWindow._dataProvider.OrderList[j].Tid != 0)
                {
                    if (mainWindow._dataProvider.OrderList[j].Status == cfg.Active)
                    {
                        if (mainWindow._dataProvider.OrderList[j].Seccode == _pM.Seccode &&
                          mainWindow._dataProvider.OrderList[j].Account == _pM.Account &&
                          mainWindow._dataProvider.OrderList[j].ClientCode == _pM.ClientCode

                            )
                            //if (mainWindow._dataProvider.OrderBlockingItems.Where(a => a.Account == _pM.Account && a.ClientCode == _pM.ClientCode).ToList().Count == 0)
                            //{
                                cfg.SetLog("Снятие заявки при нулевой позиции. ", mainWindow.ListBox_Logs);
                                CancelOrder(mainWindow._dataProvider.OrderList[j]);
                            //}
                    }
                }
            } 
            for (int j = 0; j < mainWindow._dataProvider.StopOrderList.Count; j++)
            {
                if (mainWindow._dataProvider.StopOrderList[j].TID != 0)
                {
                    if (mainWindow._dataProvider.StopOrderList[j].Status == cfg.Active)
                    {
                        if (mainWindow._dataProvider.StopOrderList[j].Seccode == _pM.Seccode &&
                          mainWindow._dataProvider.StopOrderList[j].TradeAccount == _pM.Account &&
                          mainWindow._dataProvider.StopOrderList[j].ClientCode == _pM.ClientCode)
                        {
                            bool iscancel = false;
                            //for (int s = 0; s < mainWindow._dataProvider.StopOrderBlockingItems.Count; s++)
                            //{
                            //    if (mainWindow._dataProvider.StopOrderBlockingItems[s].ClientCode == mainWindow._dataProvider.StopOrderList[j].ClientCode &&
                            //        mainWindow._dataProvider.StopOrderBlockingItems[s].Number == mainWindow._dataProvider.StopOrderList[j].Number &&
                            //        mainWindow._dataProvider.StopOrderBlockingItems[s].Seccode == mainWindow._dataProvider.StopOrderList[j].Seccode)
                            //        iscancel = true;
                            //    if (mainWindow._dataProvider.StopOrderBlockingItems[s].Number == 0 &&
                            //        mainWindow._dataProvider.StopOrderBlockingItems[s].ClientCode == mainWindow._dataProvider.StopOrderList[j].ClientCode &&
                            //        mainWindow._dataProvider.StopOrderBlockingItems[s].Seccode == mainWindow._dataProvider.StopOrderList[j].Seccode)
                            //        iscancel = true;
                            //}
                            if (iscancel == false && DateTime.Now.Day == mainWindow._dataProvider.StopOrderList[j].Time.Day &&
                               (mainWindow._dataProvider.StopOrderList[j].TimeKillOrRemove == new TimeSpan(0, 0, 0) || (mainWindow._dataProvider.StopOrderList[j].TimeKillOrRemove + new TimeSpan(0, 0, 5)) < DateTime.Now.TimeOfDay))
                            {
                                cfg.SetLog("Снятие стоп-заявки при нулевой позиции. ", mainWindow.ListBox_Logs);
                                CancelStop(mainWindow._dataProvider.StopOrderList[j]);
                                mainWindow._dataProvider.StopOrderList[j].TimeKillOrRemove = DateTime.Now.TimeOfDay;
                            }
                        }
                    }
                }
            }

            // Удаление, Снятие стоп-лосов
            List<StopOrderModel> res_Stop = new List<StopOrderModel>();
            for (int i = 0; i < mainWindow._dataProvider.StopLossOrderList.Count; i++)
            {
                if (mainWindow._dataProvider.StopLossOrderList[i].Seccode == _pM.Seccode &&
                    mainWindow._dataProvider.StopLossOrderList[i].TradeAccount == _pM.Account &&
                    mainWindow._dataProvider.StopLossOrderList[i].ClientCode == _pM.ClientCode)
                {
                    //if (mainWindow._dataProvider.StopLossOrderList[i].Status == cfg.ACTIVE)
                    //    this.CancelStop(mainWindow._dataProvider.StopLossOrderList[i]);
                }
                else
                    res_Stop.Add(mainWindow._dataProvider.StopLossOrderList[i]);
            }

            foreach (var tmp in mainWindow._dataProvider.TakeOrderList)
            {
                if (tmp.Status == cfg.Active)
                    this.CancelOrder(tmp);
            }

            mainWindow._dataProvider.DealSOrderList = res_Deal;
            mainWindow._dataProvider.StopLossOrderList = res_Stop;
        }

        /// <summary>
        /// Загрузка выставленных стоп-заявок по TID
        /// </summary>
        private void Load()
        {
            bool flagStop = false;
            bool flagTake = false;
            for (int i = 0; i < mainWindow._dataProvider.StopLossOrderList.Count; i++)
            {
                for (int j = 0; j < mainWindow._dataProvider.StopOrderList.Count; j++)
                    if (mainWindow._dataProvider.StopLossOrderList[i].TID == mainWindow._dataProvider.StopOrderList[j].TID)
                    {
                        flagStop = true;
                        mainWindow._dataProvider.StopLossOrderList[i] = mainWindow._dataProvider.StopOrderList[j];
                    }
                if (flagStop == false)
                {
                    if (mainWindow._dataProvider.StopLossOrderList[i].TimeKillOrRemove == new TimeSpan(0, 0, 0) || (mainWindow._dataProvider.StopLossOrderList[i].TimeKillOrRemove + new TimeSpan(0, 0, 3)) < DateTime.Now.TimeOfDay)
                    {
                        mainWindow._dataProvider.StopLossOrderList.Remove(mainWindow._dataProvider.StopLossOrderList[i]);
                        i--;
                    }
                }
            }

            for (int i = 0; i < mainWindow._dataProvider.TakeOrderList.Count; i++)
            {
                for (int j = 0; j < mainWindow._dataProvider.OrderList.Count; j++)
                    if (mainWindow._dataProvider.TakeOrderList[i].Tid == mainWindow._dataProvider.OrderList[j].Tid)
                    {
                        flagTake = true;
                        mainWindow._dataProvider.TakeOrderList[i] = mainWindow._dataProvider.OrderList[j];
                    }
                if (flagTake == false)
                {
                    mainWindow._dataProvider.OrderList.Remove(mainWindow._dataProvider.OrderList[i]);
                    i--;
                }
            }

            //если в сохарнении есть данные, а в сегодня уже нет этих данных, чтоб при первом запуске все затер
            //if (flagTake == false)
            //    mainWindow._dataProvider.TakeOrderList.Clear();
        }

        #region IsSend() for stop limit

        /// <summary>
        /// Проверка текущего массива стоп-заявок на наличие выставленых стоп заявок 
        /// по текущей ценам
        /// если нет стоп-заявки по цене и задавнным количесвом, то выставляем ее 
        /// если есть, то проверяем
        /// </summary>
        /// <param name="list">лист стоп-лоссов</param>
        /// <param name="sprice">Цена по которой идет проверка</param>
        /// <returns> true - надо ставить стоп-лосс, false - не надо ставить стоп-лосс</returns>
        private bool IsSend(List<StopOrderModel> list, SPrice sprice)
        {
            bool result = false;
            list = list.Where(a => a.Status != cfg.Cancel).ToList();
            //List<StopOrderModel> stoplist = list.Where(a => a.StopPrice == sprice.Stopprice).Where(a => a.Price == sprice.Price).ToList();
            List<StopOrderModel> stoplist = list;
            List<StopOrderModel> nulls = list.Where(a => a.Status == null).ToList();
            List<StopOrderModel> performed = list.Where(a => a.Status == cfg.Performed).Where(a => a.Result == cfg.AddToTs).ToList();
            List<StopOrderModel> remove_from_ts = list.Where(a => a.Status == cfg.Performed).Where(a => a.Result == cfg.RemoveFormTs).ToList();

            if (performed.Count != 0)
            {
                for (int i = 0; i < performed.Count; i++)
                {
                    // если заявка снята, то выставить
                    for (int j = mainWindow._dataProvider.OrderList.Count - 1; j >= 0; j--)
                    {
                        if (performed[i].NumberOrder == mainWindow._dataProvider.OrderList[j].Number)
                        {
                            if (mainWindow._dataProvider.OrderList[j].Status == cfg.Cancel || (mainWindow._dataProvider.OrderList[j].Status == cfg.Performed && (mainWindow._dataProvider.OrderList[j].Time.TimeOfDay + new TimeSpan(0, 0, 2) < DateTime.Now.TimeOfDay )))
                            {
                                result = true;
                                mainWindow._dataProvider.StopLossOrderList = mainWindow._dataProvider.StopLossOrderList.Where(a => a != performed[i]).ToList();
                                break;
                            }
                            if (mainWindow._dataProvider.OrderList[j].Status == cfg.Active)
                            {
                                if (mainWindow._dataProvider.OrderList[j].OstCount != Math.Abs(positionModel.Count) ||
                                    mainWindow._dataProvider.OrderList[j].Operation != (positionModel.Count < 0 ? cfg.Buy : cfg.Sell))
                                {
                                    if (mainWindow._dataProvider.OrderList[j].OstCount != Math.Abs(positionModel.Count))
                                        cfg.SetLog("   Счет: " + mainWindow._dataProvider.OrderList[j].ClientCode + " Перевыставление стоп-заявки. Текущая позиция в стоп-заявке: " +
                                        mainWindow._dataProvider.OrderList[j].Count +
                                        " Текущая позиция по счету: " + positionModel.Count, mainWindow.ListBox_Logs);
                                    if (mainWindow._dataProvider.OrderList[j].Operation != (positionModel.Count < 0 ? cfg.Buy : cfg.Sell))
                                        cfg.SetLog("   Счет: " + mainWindow._dataProvider.OrderList[j].ClientCode + " Перевыставление стоп-заявки. Текущая операция в стоп-заявке: " +
                                        mainWindow._dataProvider.OrderList[j].Operation +
                                        " Необходимая операция: " + (positionModel.Count < 0 ? cfg.Buy : cfg.Sell), mainWindow.ListBox_Logs);

                                    this.CancelOrder(mainWindow._dataProvider.OrderList[j]);
                                    mainWindow._dataProvider.OrderList[j].Status = cfg.Cancel;
                                    return false;
                                }
                            }
                        }
                    }
                }
            }
            else
            {
                if (nulls.Count != 0)
                {
                    result = false;
                }
                else
                {
                    if (stoplist.Count == 0 || remove_from_ts.Count > 0)
                    {
                        result = true;
                        cfg.SetLog("   Количество стоп-заявок по счету равно нулю", mainWindow.ListBox_Logs);
                        //cfg.SetLog("Снятие стоп-заявки. Цена расчетная отличается от текущей цены в стоп зявке. Расчетная стоп-цена " +
                        //    sprice.Stopprice + " Цена исполнения: " + sprice.Price, mainWindow.ListBox_Logs);
                    }
                    else
                    {
                        DealModel deal = this.Search(
                                           mainWindow._dataProvider.DealList,
                                           mainWindow._dataProvider.DealSOrderList);
                        for (int i = 0; i < stoplist.Count; i++)
                        {
                            if (stoplist[i].TimeKillOrRemove == new TimeSpan(0, 0, 0) || (stoplist[i].TimeKillOrRemove + new TimeSpan(0, 0, 2)) < DateTime.Now.TimeOfDay)
                            {
                                if (stoplist[i].StopPrice != sprice.Stopprice && deal.Price == sprice.Stopprice)
                                {
                                    cfg.SetLog("   Счет: " + stoplist[i].ClientCode + " Перевыставление стоп-заявки в безубыток. Текущая цена в стоп-заявке: " +
                                    stoplist[i].StopPrice +
                                    " Цена поеследней сделки " + deal.Price, mainWindow.ListBox_Logs);
                                    result = true;
                                }
                                if (stoplist[i].StopPrice != sprice.Stopprice && deal.Price != sprice.Stopprice)
                                {
                                    cfg.SetLog("   Счет: " + stoplist[i].ClientCode + " Перевыставление стоп-заявки в при изменении отсупа в программе. Текущая цена в стоп-заявке: " +
                                    stoplist[i].StopPrice +
                                    " Цена поеследней сделки " + deal.Price, mainWindow.ListBox_Logs);
                                    result = true;
                                }
                                if (stoplist[i].Count != Math.Abs(positionModel.Count))
                                {
                                    result = true;
                                    cfg.SetLog("   Счет: " + stoplist[i].ClientCode + " Перевыставление стоп-заявки. Текущая позиция в стоп-заявке: " +
                                    stoplist[i].Count +
                                    " Текущая позиция по счету: " + positionModel.Count, mainWindow.ListBox_Logs);
                                }
                                if (stoplist[i].Operation != (positionModel.Count < 0 ? cfg.Buy : cfg.Sell))
                                {
                                    cfg.SetLog("   Счет: " + stoplist[i].ClientCode + " Перевыставление стоп-заявки. Текущая операция в стоп-заявке: " +
                                    stoplist[i].Operation +
                                    " Необходимая операция: " + (positionModel.Count < 0 ? cfg.Buy : cfg.Sell), mainWindow.ListBox_Logs);
                                    result = true;
                                }
                            }
                        }
                    }
                }
            }

            #region Если надо выставить стоп-заявку, то снимаем все активные стоп-заявки и заявки

            if (result == true)
            {
                for (int i = 0; i < list.Count; i++)
                {
                    if (list[i].Status == cfg.Active)
                    {
                        if (list[i].Time.Date == DateTime.Now.Date)
                        {
                            if ((list[i].TimeKillOrRemove + new TimeSpan(0, 0, 2)) < DateTime.Now.TimeOfDay)
                            {
                                this.CancelStop(list[i]);
                                list[i].TimeKillOrRemove = DateTime.Now.TimeOfDay;
                            }
                        }
                    }
                }
            }

            #endregion

            return result;
        }
        #endregion

        #region IsSend() for take profit

        private bool IsSend(StopListModel stop, List<StopOrderModel> list, SPrice sprice)
        {
            bool result = false;
            this.Load();

            List<StopOrderModel> stoplist = list.Where(a => a.StopPrice == sprice.Stopprice).Where(a => a.OtsupMaxMin == stop.TakeOtst).Where(a => a.Spread == stop.TakeSprd).ToList();
            List<StopOrderModel> nulls = list.Where(a => a.Status == null).ToList();
            List<StopOrderModel> performed = list.Where(a => a.Status == cfg.Performed).Where(a => a.Result == cfg.AddToTs).ToList();

            if (performed.Count != 0)
            {
                for (int i = 0; i < performed.Count; i++)
                {
                    // если заявка снята, то выставить
                    for (int j = mainWindow._dataProvider.OrderList.Count - 1; j >= 0; j--)
                    {
                        if (performed[i].NumberOrder == mainWindow._dataProvider.OrderList[j].Number)
                        {
                            if (mainWindow._dataProvider.OrderList[j].Status == cfg.Cancel || mainWindow._dataProvider.OrderList[j].Status == cfg.Performed)
                            {
                                result = true;
                                mainWindow._dataProvider.StopLossOrderList = mainWindow._dataProvider.StopLossOrderList.Where(a => a != performed[i]).ToList();
                                break;
                            }
                            if (mainWindow._dataProvider.OrderList[j].Status == cfg.Active)
                            {

                                if (mainWindow._dataProvider.OrderList[j].Count != Math.Abs(positionModel.Count) ||
                                    mainWindow._dataProvider.OrderList[j].Operation != (positionModel.Count < 0 ? cfg.Buy : cfg.Sell))
                                {

                                    this.CancelOrder(mainWindow._dataProvider.OrderList[j]);
                                    mainWindow._dataProvider.OrderList[j].Status = cfg.Cancel;
                                    return false;
                                }
                            }
                        }
                    }
                }
            }
            else
            {
                if (nulls.Count != 0)
                {
                    result = false;
                }
                else
                {
                    if (stoplist.Count == 0)
                        result = true;
                    else
                    {
                        for (int i = 0; i < stoplist.Count; i++)
                        {
                            if (stoplist[i].Count != Math.Abs(positionModel.Count))
                                result = true;
                        }
                    }
                }
            }

            #region Если надо выставить стоп-заявку, то снимаем все активные стоп-заявки и заявки

            if (result == true)
            {
                for (int i = 0; i < list.Count; i++)
                {
                    if (list[i].Status == cfg.Active)
                        this.CancelStop(list[i]);

                    //if (list[i].Status == cfg.PERFORMED && list[i].Result == cfg.ADD_TO_TS)
                    //{
                    //    //for (int j = mainwindow._dataprovider.orderlist)
                    //}
                }
            }

            #endregion
            return result;
        }

        #endregion

        #region IsSend() for stop and take order

        private bool IsSend(StopListModel stopListModel, List<StopOrderModel> list, SPrice take_sprice, SPrice stop_sprice)
        {
            bool result = false;

            this.Load();

            List<StopOrderModel> stoplist = list.Where(a => a.StopPrice == take_sprice.Stopprice).
                                                 Where(a => a.Price == stop_sprice.Price).
                                                 Where(a => a.OtsupMaxMin == stopListModel.TakeOtst).
                                                 Where(a => a.Spread == stopListModel.TakeSprd).ToList();

            List<StopOrderModel> nulls = list.Where(a => a.Status == null).ToList();
            List<StopOrderModel> performed = list.Where(a => a.Status == cfg.Performed).
                                                  Where(a => a.Result == cfg.AddToTs).ToList();

            if (performed.Count != 0)
            {
                for (int i = 0; i < performed.Count; i++)
                {
                    // если заявка снята, то выставить
                    for (int j = mainWindow._dataProvider.OrderList.Count - 1; j >= 0; j--)
                    {
                        if (performed[i].NumberOrder == mainWindow._dataProvider.OrderList[j].Number)
                        {
                            if (mainWindow._dataProvider.OrderList[j].Status == cfg.Cancel ||
                                mainWindow._dataProvider.OrderList[j].Status == cfg.Performed)
                            {
                                result = true;
                                mainWindow._dataProvider.StopLossOrderList = mainWindow._dataProvider.StopLossOrderList.Where(a => a != performed[i]).ToList();
                                break;
                            }
                            if (mainWindow._dataProvider.OrderList[j].Status == cfg.Active)
                            {
                                if (mainWindow._dataProvider.OrderList[j].Count != Math.Abs(positionModel.Count) ||
                                    mainWindow._dataProvider.OrderList[j].Operation != (positionModel.Count < 0 ? cfg.Buy : cfg.Sell))
                                {

                                    this.CancelOrder(mainWindow._dataProvider.OrderList[j]);
                                    mainWindow._dataProvider.OrderList[j].Status = cfg.Cancel;
                                    return false;
                                }
                            }
                        }
                    }
                }
            }
            else
            {
                if (nulls.Count != 0)
                {
                    result = false;
                }
                else
                {
                    if (stoplist.Count == 0)
                        result = true;
                    else
                    {
                        for (int i = 0; i < stoplist.Count; i++)
                        {
                            if (stoplist[i].Count != Math.Abs(positionModel.Count))
                                result = true;
                        }
                    }
                }
            }

            #region Если надо выставить стоп-заявку, то снимаем все активные стоп-заявки и заявки

            if (result == true)
            {
                for (int i = 0; i < list.Count; i++)
                {
                    if (list[i].Status == cfg.Active)
                        this.CancelStop(list[i]);

                    //if (list[i].Status == cfg.PERFORMED && list[i].Result == cfg.ADD_TO_TS)
                    //{
                    //    //for (int j = mainwindow._dataprovider.orderlist)
                    //}
                }
            }

            #endregion
            return result;
        }

        #endregion

        #region IsSend() for linked order


        private bool IsSendLinked(StopListModel stopListModel, List<StopOrderModel> list, SPrice stop_sprice, SPrice take_sprice)
        {
            bool result = false;

            this.Load();

            List<StopOrderModel> stoplist = list.Where(a => a.StopPrice == stop_sprice.Stopprice).Where(a => a.Price == stop_sprice.Price).ToList();

            List<StopOrderModel> nulls = list.Where(a => a.Status == null).ToList();
            List<StopOrderModel> performed = list.Where(a => a.Status == cfg.Performed).Where(a => a.Result == cfg.AddToTs).ToList();

            if (performed.Count != 0)
            {
                for (int i = 0; i < performed.Count; i++)
                {
                    for (int j = mainWindow._dataProvider.OrderList.Count - 1; j >= 0; j--)
                    {
                        if (performed[i].NumberOrder == mainWindow._dataProvider.OrderList[j].Number)
                        {
                            if (mainWindow._dataProvider.OrderList[j].Status == cfg.Cancel ||
                                mainWindow._dataProvider.OrderList[j].Status == cfg.Performed)
                            {
                                result = true;
                                mainWindow._dataProvider.StopLossOrderList = mainWindow._dataProvider.StopLossOrderList.Where(a => a != performed[i]).ToList();
                                break;
                            }
                            if (mainWindow._dataProvider.OrderList[j].Status == cfg.Active)
                            {
                                if (mainWindow._dataProvider.OrderList[j].Count != Math.Abs(positionModel.Count) ||
                                     mainWindow._dataProvider.OrderList[j].Operation != (positionModel.Count < 0 ? cfg.Buy : cfg.Sell))
                                {
                                    this.CancelOrder(mainWindow._dataProvider.OrderList[j]);
                                    return false;
                                }
                            }
                        }
                    }
                }
            }
            else
            {
                if (nulls.Count != 0)
                {
                    result = false;
                }
                else
                {
                    if (stoplist.Count == 0)
                        result = true;
                    else
                    {
                        for (int i = 0; i < stoplist.Count; i++)
                        {
                            if (stoplist[i].Count != Math.Abs(positionModel.Count))
                                result = true;
                        }
                    }
                }
            }

            #region Если надо выставить стоп-заявку, то снимаем все активные стоп-заявки и заявки

            if (result == true)
            {
                for (int i = 0; i < list.Count; i++)
                {
                    if (list[i].Status == cfg.Active)
                        this.CancelStop(list[i]);

                    //if (list[i].Status == cfg.PERFORMED && list[i].Result == cfg.ADD_TO_TS)
                    //{
                    //    //for (int j = mainwindow._dataprovider.orderlist)
                    //}
                }
            }

            #endregion
            return result;
        }

        #endregion

        #region IsSend() for take profit

        private bool IsSendTakeLimit(StopListModel stop, List<OrderModel> list, SPrice sprice)
        {
            bool result = false;
            this.Load();

            List<OrderModel> stoplist = list.Where(a => a.Price == sprice.Stopprice).ToList();
            List<OrderModel> nulls = list.Where(a => a.Status == null).ToList();
            List<OrderModel> performed = list.Where(a => a.Status == cfg.Performed).ToList();

            if (performed.Count != 0)
            {

                for (int i = 0; i < performed.Count; i++)
                {
                    // если заявка снята, то выставить
                    for (int j = mainWindow._dataProvider.OrderList.Count - 1; j >= 0; j--)
                    {
                        if (performed[i].Number == mainWindow._dataProvider.OrderList[j].Number)
                        {
                            if (mainWindow._dataProvider.OrderList[j].Status == cfg.Cancel ||
                                mainWindow._dataProvider.OrderList[j].Status == cfg.Performed)
                            {
                                result = true;
                                break;
                            }
                            if (mainWindow._dataProvider.OrderList[j].Status == cfg.Active)
                            {
                                if (mainWindow._dataProvider.OrderList[j].Count != Math.Abs(positionModel.Count) ||
                                    mainWindow._dataProvider.OrderList[j].Operation != (positionModel.Count < 0 ? cfg.Buy : cfg.Sell))
                                {

                                    this.CancelOrder(mainWindow._dataProvider.OrderList[j]);
                                    mainWindow._dataProvider.OrderList[j].Status = cfg.Cancel;
                                    return false;
                                }
                            }
                        }
                    }
                    // return false;
                }
            }
            else
            {
                if (nulls.Count != 0)
                {
                    result = false;
                }
                else
                {
                    if (stoplist.Count == 0)
                        result = true;
                    else
                    {
                        for (int i = 0; i < stoplist.Count; i++)
                        {
                            if (stoplist[i].Count != Math.Abs(positionModel.Count))
                                result = true;
                        }
                    }
                }
            }

            #region Если надо выставить стоп-заявку, то снимаем все активные стоп-заявки и заявки

            if (result == true)
            {
                for (int i = 0; i < list.Count; i++)
                {
                    if (list[i].Status == cfg.Active)
                        mainWindow.Terminals.TransQuikItems_0.CancelOrder(list[i].Number, list[i].Seccode, mainWindow._dataProvider.GetClasscode(list[i].Seccode));
                    //if (list[i].Status == cfg.PERFORMED && list[i].Result == cfg.ADD_TO_TS)
                    //{
                    //    //for (int j = mainwindow._dataprovider.orderlist)
                    //}
                }
            }

            #endregion
            return result;
        }
        #endregion

        private string GetStatus(long number, List<Models.OrderModel> list)
        {
            for (int i = 0; i < list.Count; i++)
                if (list[i].Number == number)
                    return list[i].Status;

            return cfg.Unknown;
        }

        private char getOperation(DealModel deal)
        {
            if (deal.Operation == cfg.Buy)
                return 'S';
            if (deal.Operation == cfg.Sell)
                return 'B';

            return '0';
        }

        #region транзакции: отправление

        public void SendOrder(char op, Double stopprice, int lot, DealModel deal, double offset, double spread, String units)
        {
            int tid = 0;

            for (int i = 0; i < mainWindow._dataProvider.T2QItems.Count; i++)
            {
                for (int j = 0; j < mainWindow._dataProvider.T2QItems[i].TradeList.Count; j++)
                {
                    if (mainWindow._dataProvider.T2QItems[i].TradeList[j].Account == deal.Account &&
                        mainWindow._dataProvider.T2QItems[i].TradeList[j].ClientCode == deal.ClientCode)
                    {
                        if (i == 0)
                            tid = mainWindow.Terminals.TransQuikItems_0.SendOrder(op, stopprice, lot, deal.Seccode, deal.ClassCode, deal.Account, deal.ClientCode + "//Stops");
                        if (i == 1)
                            tid = mainWindow.Terminals.TransQuikItems_1.SendOrder(op, stopprice, lot, deal.Seccode, deal.ClassCode, deal.Account, deal.ClientCode + "//Stops");
                        if (i == 2)
                            tid = mainWindow.Terminals.TransQuikItems_2.SendOrder(op, stopprice, lot, deal.Seccode, deal.ClassCode, deal.Account, deal.ClientCode + "//Stops");
                        if (i == 3)
                            tid = mainWindow.Terminals.TransQuikItems_3.SendOrder(op, stopprice, lot, deal.Seccode, deal.ClassCode, deal.Account, deal.ClientCode + "//Stops");
                        if (i == 4)
                            tid = mainWindow.Terminals.TransQuikItems_4.SendOrder(op, stopprice, lot, deal.Seccode, deal.ClassCode, deal.Account, deal.ClientCode + "//Stops");
                        if (i == 5)
                            tid = mainWindow.Terminals.TransQuikItems_5.SendOrder(op, stopprice, lot, deal.Seccode, deal.ClassCode, deal.Account, deal.ClientCode + "//Stops");
                        if (i == 6)
                            tid = mainWindow.Terminals.TransQuikItems_6.SendOrder(op, stopprice, lot, deal.Seccode, deal.ClassCode, deal.Account, deal.ClientCode + "//Stops");
                        if (i == 7)
                            tid = mainWindow.Terminals.TransQuikItems_7.SendOrder(op, stopprice, lot, deal.Seccode, deal.ClassCode, deal.Account, deal.ClientCode + "//Stops");
                        if (i == 8)
                            tid = mainWindow.Terminals.TransQuikItems_8.SendOrder(op, stopprice, lot, deal.Seccode, deal.ClassCode, deal.Account, deal.ClientCode + "//Stops");
                        if (i == 9)
                            tid = mainWindow.Terminals.TransQuikItems_9.SendOrder(op, stopprice, lot, deal.Seccode, deal.ClassCode, deal.Account, deal.ClientCode + "//Stops");
                    }
                }
            }

            mainWindow._dataProvider.TakeOrderList.Add(new OrderModel()
            {
                Tid = tid,
                Seccode = deal.Seccode,
                Account = deal.Account,
                ClientCode = deal.ClientCode,
                Price = stopprice,
                Count = lot,
                Status = cfg.Active
            });
        }

        public void SendLinkedStop(char op, SPrice sp, SPrice pr, int lt, DealModel deal)
        {
            int tid = 0;

            for (int i = 0; i < mainWindow._dataProvider.T2QItems.Count; i++)
            {
                for (int j = 0; j < mainWindow._dataProvider.T2QItems[i].TradeList.Count; j++)
                {
                    if (mainWindow._dataProvider.T2QItems[i].TradeList[j].Account == deal.Account &&
                        mainWindow._dataProvider.T2QItems[i].TradeList[j].ClientCode == deal.ClientCode)
                    {
                        if (i == 0)
                            tid = mainWindow.Terminals.TransQuikItems_0.SendLinkedOrder(deal.Account, deal.ClassCode, deal.Seccode, op, lt, deal.ClientCode + "//Stops", sp.Stopprice, sp.Price, pr.Stopprice);
                        if (i == 1)
                            tid = mainWindow.Terminals.TransQuikItems_1.SendLinkedOrder(deal.Account, deal.ClassCode, deal.Seccode, op, lt, deal.ClientCode + "//Stops", sp.Stopprice, sp.Price, pr.Stopprice);
                        if (i == 2)
                            tid = mainWindow.Terminals.TransQuikItems_2.SendLinkedOrder(deal.Account, deal.ClassCode, deal.Seccode, op, lt, deal.ClientCode + "//Stops", sp.Stopprice, sp.Price, pr.Stopprice);
                        if (i == 3)
                            tid = mainWindow.Terminals.TransQuikItems_3.SendLinkedOrder(deal.Account, deal.ClassCode, deal.Seccode, op, lt, deal.ClientCode + "//Stops", sp.Stopprice, sp.Price, pr.Stopprice);
                        if (i == 4)
                            tid = mainWindow.Terminals.TransQuikItems_4.SendLinkedOrder(deal.Account, deal.ClassCode, deal.Seccode, op, lt, deal.ClientCode + "//Stops", sp.Stopprice, sp.Price, pr.Stopprice);
                        if (i == 5)
                            tid = mainWindow.Terminals.TransQuikItems_5.SendLinkedOrder(deal.Account, deal.ClassCode, deal.Seccode, op, lt, deal.ClientCode + "//Stops", sp.Stopprice, sp.Price, pr.Stopprice);
                        if (i == 6)
                            tid = mainWindow.Terminals.TransQuikItems_6.SendLinkedOrder(deal.Account, deal.ClassCode, deal.Seccode, op, lt, deal.ClientCode + "//Stops", sp.Stopprice, sp.Price, pr.Stopprice);
                        if (i == 7)
                            tid = mainWindow.Terminals.TransQuikItems_7.SendLinkedOrder(deal.Account, deal.ClassCode, deal.Seccode, op, lt, deal.ClientCode + "//Stops", sp.Stopprice, sp.Price, pr.Stopprice);
                        if (i == 8)
                            tid = mainWindow.Terminals.TransQuikItems_8.SendLinkedOrder(deal.Account, deal.ClassCode, deal.Seccode, op, lt, deal.ClientCode + "//Stops", sp.Stopprice, sp.Price, pr.Stopprice);
                        if (i == 9)
                            tid = mainWindow.Terminals.TransQuikItems_9.SendLinkedOrder(deal.Account, deal.ClassCode, deal.Seccode, op, lt, deal.ClientCode + "//Stops", sp.Stopprice, sp.Price, pr.Stopprice);
                    }
                }
            }

            mainWindow._dataProvider.StopLossOrderList.Add(new StopOrderModel()
            {
                TID = tid,
                Seccode = deal.Seccode,
                TradeAccount = deal.Account,
                ClientCode = deal.ClientCode,
                TypeStop = cfg.LinkedOOrder,
                Count = lt
            });
        }

        public void SendStop(char op, Double sp, double pr, int lt, DealModel deal)
        {
            int tid = 0;

            for (int i = 0; i < mainWindow._dataProvider.T2QItems.Count; i++)
            {
                for (int j = 0; j < mainWindow._dataProvider.T2QItems[i].TradeList.Count; j++)
                {
                    if (mainWindow._dataProvider.T2QItems[i].TradeList[j].Account == deal.Account &&
                        mainWindow._dataProvider.T2QItems[i].TradeList[j].ClientCode == deal.ClientCode)
                    {
                        if (i == 0)
                            tid = mainWindow.Terminals.TransQuikItems_0.SendStopOrder(op, sp, pr, lt, deal.Seccode, deal.ClassCode, deal.Account, deal.ClientCode + "//Stops");
                        if (i == 1)
                            tid = mainWindow.Terminals.TransQuikItems_1.SendStopOrder(op, sp, pr, lt, deal.Seccode, deal.ClassCode, deal.Account, deal.ClientCode + "//Stops");
                        if (i == 2)
                            tid = mainWindow.Terminals.TransQuikItems_2.SendStopOrder(op, sp, pr, lt, deal.Seccode, deal.ClassCode, deal.Account, deal.ClientCode + "//Stops");
                        if (i == 3)
                            tid = mainWindow.Terminals.TransQuikItems_3.SendStopOrder(op, sp, pr, lt, deal.Seccode, deal.ClassCode, deal.Account, deal.ClientCode + "//Stops");
                        if (i == 4)
                            tid = mainWindow.Terminals.TransQuikItems_4.SendStopOrder(op, sp, pr, lt, deal.Seccode, deal.ClassCode, deal.Account, deal.ClientCode + "//Stops");
                        if (i == 5)
                            tid = mainWindow.Terminals.TransQuikItems_5.SendStopOrder(op, sp, pr, lt, deal.Seccode, deal.ClassCode, deal.Account, deal.ClientCode + "//Stops");
                        if (i == 6)
                            tid = mainWindow.Terminals.TransQuikItems_6.SendStopOrder(op, sp, pr, lt, deal.Seccode, deal.ClassCode, deal.Account, deal.ClientCode + "//Stops");
                        if (i == 7)
                            tid = mainWindow.Terminals.TransQuikItems_7.SendStopOrder(op, sp, pr, lt, deal.Seccode, deal.ClassCode, deal.Account, deal.ClientCode + "//Stops");
                        if (i == 8)
                            tid = mainWindow.Terminals.TransQuikItems_8.SendStopOrder(op, sp, pr, lt, deal.Seccode, deal.ClassCode, deal.Account, deal.ClientCode + "//Stops");
                        if (i == 9)
                            tid = mainWindow.Terminals.TransQuikItems_9.SendStopOrder(op, sp, pr, lt, deal.Seccode, deal.ClassCode, deal.Account, deal.ClientCode + "//Stops");
                    }
                }
            }

            mainWindow._dataProvider.StopLossOrderList.Add(new StopOrderModel()
            {
                TID = tid,
                Seccode = deal.Seccode,
                TradeAccount = deal.Account,
                ClientCode = deal.ClientCode,
                TypeStop = cfg.StopLimit,
                Status = null,
                Count = lt,
                TimeKillOrRemove = DateTime.Now.TimeOfDay
            });
        }

        //Перезагруженный метод отправки стоп-заявки, используется в начале торгов, если есть позиция по иснтрументу и нет сделок по этому инструменту, по счету.
        public void SendStop(char op, Double sp, double pr, int lt, string Seccode, string ClassCode, string Account, string ClientCode)
        {
            int tid = 0;

            for (int i = 0; i < mainWindow._dataProvider.T2QItems.Count; i++)
            {
                for (int j = 0; j < mainWindow._dataProvider.T2QItems[i].TradeList.Count; j++)
                {
                    if (mainWindow._dataProvider.T2QItems[i].TradeList[j].Account == Account &&
                        mainWindow._dataProvider.T2QItems[i].TradeList[j].ClientCode == ClientCode)
                    {
                        if (i == 0)
                            tid = mainWindow.Terminals.TransQuikItems_0.SendStopOrder(op, sp, pr, lt, Seccode, ClassCode, Account, ClientCode + "//Stops");
                        if (i == 1)
                            tid = mainWindow.Terminals.TransQuikItems_1.SendStopOrder(op, sp, pr, lt, Seccode, ClassCode, Account, ClientCode + "//Stops");
                        if (i == 2)
                            tid = mainWindow.Terminals.TransQuikItems_2.SendStopOrder(op, sp, pr, lt, Seccode, ClassCode, Account, ClientCode + "//Stops");
                        if (i == 3)
                            tid = mainWindow.Terminals.TransQuikItems_3.SendStopOrder(op, sp, pr, lt, Seccode, ClassCode, Account, ClientCode + "//Stops");
                        if (i == 4)
                            tid = mainWindow.Terminals.TransQuikItems_4.SendStopOrder(op, sp, pr, lt, Seccode, ClassCode, Account, ClientCode + "//Stops");
                        if (i == 5)
                            tid = mainWindow.Terminals.TransQuikItems_5.SendStopOrder(op, sp, pr, lt, Seccode, ClassCode, Account, ClientCode + "//Stops");
                        if (i == 6)
                            tid = mainWindow.Terminals.TransQuikItems_6.SendStopOrder(op, sp, pr, lt, Seccode, ClassCode, Account, ClientCode + "//Stops");
                        if (i == 7)
                            tid = mainWindow.Terminals.TransQuikItems_7.SendStopOrder(op, sp, pr, lt, Seccode, ClassCode, Account, ClientCode + "//Stops");
                        if (i == 8)
                            tid = mainWindow.Terminals.TransQuikItems_8.SendStopOrder(op, sp, pr, lt, Seccode, ClassCode, Account, ClientCode + "//Stops");
                        if (i == 9)
                            tid = mainWindow.Terminals.TransQuikItems_9.SendStopOrder(op, sp, pr, lt, Seccode, ClassCode, Account, ClientCode + "//Stops");
                    }
                }
            }

            mainWindow._dataProvider.StopLossOrderList.Add(new StopOrderModel()
            {
                TID = tid,
                Seccode = Seccode,
                TradeAccount = Account,
                ClientCode = ClientCode,
                TypeStop = cfg.StopLimit,
                Status = null,
                Count = lt,
                TimeKillOrRemove = DateTime.Now.TimeOfDay
            });
        }


        public void SendTake(char op, Double stopprice, int lot, DealModel deal, double offset, double spread, String units)
        {
            int tid = 0;

            for (int i = 0; i < mainWindow._dataProvider.T2QItems.Count; i++)
            {
                for (int j = 0; j < mainWindow._dataProvider.T2QItems[i].TradeList.Count; j++)
                {
                    if (mainWindow._dataProvider.T2QItems[i].TradeList[j].Account == deal.Account &&
                        mainWindow._dataProvider.T2QItems[i].TradeList[j].ClientCode == deal.ClientCode)
                    {
                        if (i == 0)
                            tid = mainWindow.Terminals.TransQuikItems_0.SendTakeProfit(op, stopprice, deal.ClientCode + "//Stops", deal.Seccode, deal.ClassCode, deal.Account, lot, offset, spread, units);
                        if (i == 1)
                            tid = mainWindow.Terminals.TransQuikItems_1.SendTakeProfit(op, stopprice, deal.ClientCode + "//Stops", deal.Seccode, deal.ClassCode, deal.Account, lot, offset, spread, units);
                        if (i == 2)
                            tid = mainWindow.Terminals.TransQuikItems_2.SendTakeProfit(op, stopprice, deal.ClientCode + "//Stops", deal.Seccode, deal.ClassCode, deal.Account, lot, offset, spread, units);
                        if (i == 3)
                            tid = mainWindow.Terminals.TransQuikItems_3.SendTakeProfit(op, stopprice, deal.ClientCode + "//Stops", deal.Seccode, deal.ClassCode, deal.Account, lot, offset, spread, units);
                        if (i == 4)
                            tid = mainWindow.Terminals.TransQuikItems_4.SendTakeProfit(op, stopprice, deal.ClientCode + "//Stops", deal.Seccode, deal.ClassCode, deal.Account, lot, offset, spread, units);
                        if (i == 5)
                            tid = mainWindow.Terminals.TransQuikItems_5.SendTakeProfit(op, stopprice, deal.ClientCode + "//Stops", deal.Seccode, deal.ClassCode, deal.Account, lot, offset, spread, units);
                        if (i == 6)
                            tid = mainWindow.Terminals.TransQuikItems_6.SendTakeProfit(op, stopprice, deal.ClientCode + "//Stops", deal.Seccode, deal.ClassCode, deal.Account, lot, offset, spread, units);
                        if (i == 7)
                            tid = mainWindow.Terminals.TransQuikItems_7.SendTakeProfit(op, stopprice, deal.ClientCode + "//Stops", deal.Seccode, deal.ClassCode, deal.Account, lot, offset, spread, units);
                        if (i == 8)
                            tid = mainWindow.Terminals.TransQuikItems_8.SendTakeProfit(op, stopprice, deal.ClientCode + "//Stops", deal.Seccode, deal.ClassCode, deal.Account, lot, offset, spread, units);
                        if (i == 9)
                            tid = mainWindow.Terminals.TransQuikItems_9.SendTakeProfit(op, stopprice, deal.ClientCode + "//Stops", deal.Seccode, deal.ClassCode, deal.Account, lot, offset, spread, units);
                    }
                }
            }


            mainWindow._dataProvider.StopLossOrderList.Add(new StopOrderModel()
            {
                TID = tid,
                Seccode = deal.Seccode,
                TradeAccount = deal.Account,
                ClientCode = deal.ClientCode,
                Spread = spread,
                OtsupMaxMin = offset,
                TypeStop = cfg.TakeProfit,
                Status = null,
                Count = lot
            });
        }

        public void CancelStop(StopOrderModel order)
        {
            for (int i = 0; i < mainWindow._dataProvider.T2QItems.Count; i++)
            {
                for (int j = 0; j < mainWindow._dataProvider.T2QItems[i].TradeList.Count; j++)
                {
                    if (mainWindow._dataProvider.T2QItems[i].TradeList[j].Account == order.TradeAccount &&
                        mainWindow._dataProvider.T2QItems[i].TradeList[j].ClientCode == order.ClientCode)
                    {

                        if (i == 0)
                            mainWindow.Terminals.TransQuikItems_0.CancelStopOrder(order.Number, order.Seccode, GetClasscode(order.Seccode), order.TradeAccount, order.ClientCode);
                        if (i == 1)
                            mainWindow.Terminals.TransQuikItems_1.CancelStopOrder(order.Number, order.Seccode, GetClasscode(order.Seccode), order.TradeAccount, order.ClientCode);
                        if (i == 2)
                            mainWindow.Terminals.TransQuikItems_2.CancelStopOrder(order.Number, order.Seccode, GetClasscode(order.Seccode), order.TradeAccount, order.ClientCode);
                        if (i == 3)
                            mainWindow.Terminals.TransQuikItems_3.CancelStopOrder(order.Number, order.Seccode, GetClasscode(order.Seccode), order.TradeAccount, order.ClientCode);
                        if (i == 4)
                            mainWindow.Terminals.TransQuikItems_4.CancelStopOrder(order.Number, order.Seccode, GetClasscode(order.Seccode), order.TradeAccount, order.ClientCode);
                        if (i == 5)
                            mainWindow.Terminals.TransQuikItems_5.CancelStopOrder(order.Number, order.Seccode, GetClasscode(order.Seccode), order.TradeAccount, order.ClientCode);
                        if (i == 6)
                            mainWindow.Terminals.TransQuikItems_6.CancelStopOrder(order.Number, order.Seccode, GetClasscode(order.Seccode), order.TradeAccount, order.ClientCode);
                        if (i == 7)
                            mainWindow.Terminals.TransQuikItems_7.CancelStopOrder(order.Number, order.Seccode, GetClasscode(order.Seccode), order.TradeAccount, order.ClientCode);
                        if (i == 8)
                            mainWindow.Terminals.TransQuikItems_8.CancelStopOrder(order.Number, order.Seccode, GetClasscode(order.Seccode), order.TradeAccount, order.ClientCode);
                        if (i == 9)
                            mainWindow.Terminals.TransQuikItems_9.CancelStopOrder(order.Number, order.Seccode, GetClasscode(order.Seccode), order.TradeAccount, order.ClientCode);
                    }
                }
            }

            //mainWindow.ListBox_Logs.Items.Add("Снятие стоп-заявки " + order.Number + " по счету: " + order.ClientCode + " Инструмент: " + order.Seccode);
            //mainWindow._dataProvider.StopLossOrderList.Remove(order);

        }

        public void CancelOrder(OrderModel order)
        {

            for (int i = 0; i < mainWindow._dataProvider.T2QItems.Count; i++)
                for (int j = 0; j < mainWindow._dataProvider.T2QItems[i].TradeList.Count; j++)
                {
                    if (mainWindow._dataProvider.T2QItems[i].TradeList[j].Account == order.Account &&
                        mainWindow._dataProvider.T2QItems[i].TradeList[j].ClientCode == order.ClientCode)
                    {
                        if (i == 0)
                            mainWindow.Terminals.TransQuikItems_0.CancelOrder(order.Number, order.Seccode, GetClasscode(order.Seccode));
                        if (i == 1)
                            mainWindow.Terminals.TransQuikItems_1.CancelOrder(order.Number, order.Seccode, GetClasscode(order.Seccode));
                        if (i == 2)
                            mainWindow.Terminals.TransQuikItems_2.CancelOrder(order.Number, order.Seccode, GetClasscode(order.Seccode));
                        if (i == 3)
                            mainWindow.Terminals.TransQuikItems_3.CancelOrder(order.Number, order.Seccode, GetClasscode(order.Seccode));
                        if (i == 4)
                            mainWindow.Terminals.TransQuikItems_4.CancelOrder(order.Number, order.Seccode, GetClasscode(order.Seccode));
                        if (i == 5)
                            mainWindow.Terminals.TransQuikItems_5.CancelOrder(order.Number, order.Seccode, GetClasscode(order.Seccode));
                        if (i == 6)
                            mainWindow.Terminals.TransQuikItems_6.CancelOrder(order.Number, order.Seccode, GetClasscode(order.Seccode));
                        if (i == 7)
                            mainWindow.Terminals.TransQuikItems_7.CancelOrder(order.Number, order.Seccode, GetClasscode(order.Seccode));
                        if (i == 8)
                            mainWindow.Terminals.TransQuikItems_8.CancelOrder(order.Number, order.Seccode, GetClasscode(order.Seccode));
                        if (i == 9)
                            mainWindow.Terminals.TransQuikItems_9.CancelOrder(order.Number, order.Seccode, GetClasscode(order.Seccode));
                    }
                }
        }

        public void SendStopTake(char op, DealModel deal, int lot, double limit_price, double take_price, double offset, string units, double spread, String byMarket, double limit_stop_price)
        {

            int tid = 0;

            for (int i = 0; i < mainWindow._dataProvider.T2QItems.Count; i++)
            {
                for (int j = 0; j < mainWindow._dataProvider.T2QItems[i].TradeList.Count; j++)
                {
                    if (mainWindow._dataProvider.T2QItems[i].TradeList[j].Account == deal.Account &&
                        mainWindow._dataProvider.T2QItems[i].TradeList[j].ClientCode == deal.ClientCode)
                    {
                        if (i == 0)
                            tid = mainWindow.Terminals.TransQuikItems_0.SendStopAndTake(op, deal.ClassCode, deal.Seccode,
                                deal.Account, deal.ClientCode + "//Stops", lot, limit_price, take_price, offset, units, spread, byMarket, limit_stop_price);

                        if (i == 1)
                            tid = mainWindow.Terminals.TransQuikItems_1.SendStopAndTake(op, deal.ClassCode, deal.Seccode,
                                deal.Account, deal.ClientCode + "//Stops", lot, limit_price, take_price, offset, units, spread, byMarket, limit_stop_price);
                        if (i == 2)
                            tid = mainWindow.Terminals.TransQuikItems_2.SendStopAndTake(op, deal.ClassCode, deal.Seccode,
                                deal.Account, deal.ClientCode + "//Stops", lot, limit_price, take_price, offset, units, spread, byMarket, limit_stop_price);
                        if (i == 3)
                            tid = mainWindow.Terminals.TransQuikItems_3.SendStopAndTake(op, deal.ClassCode, deal.Seccode,
                                deal.Account, deal.ClientCode + "//Stops", lot, limit_price, take_price, offset, units, spread, byMarket, limit_stop_price);
                        if (i == 4)
                            tid = mainWindow.Terminals.TransQuikItems_4.SendStopAndTake(op, deal.ClassCode, deal.Seccode,
                                deal.Account, deal.ClientCode + "//Stops", lot, limit_price, take_price, offset, units, spread, byMarket, limit_stop_price);
                        if (i == 5)
                            tid = mainWindow.Terminals.TransQuikItems_5.SendStopAndTake(op, deal.ClassCode, deal.Seccode,
                                deal.Account, deal.ClientCode + "//Stops", lot, limit_price, take_price, offset, units, spread, byMarket, limit_stop_price);
                        if (i == 6)
                            tid = mainWindow.Terminals.TransQuikItems_6.SendStopAndTake(op, deal.ClassCode, deal.Seccode,
                                deal.Account, deal.ClientCode + "//Stops", lot, limit_price, take_price, offset, units, spread, byMarket, limit_stop_price);
                        if (i == 7)
                            tid = mainWindow.Terminals.TransQuikItems_7.SendStopAndTake(op, deal.ClassCode, deal.Seccode,
                                deal.Account, deal.ClientCode + "//Stops", lot, limit_price, take_price, offset, units, spread, byMarket, limit_stop_price);
                        if (i == 8)
                            tid = mainWindow.Terminals.TransQuikItems_8.SendStopAndTake(op, deal.ClassCode, deal.Seccode,
                                deal.Account, deal.ClientCode + "//Stops", lot, limit_price, take_price, offset, units, spread, byMarket, limit_stop_price);
                        if (i == 9)
                            tid = mainWindow.Terminals.TransQuikItems_9.SendStopAndTake(op, deal.ClassCode, deal.Seccode,
                                deal.Account, deal.ClientCode + "//Stops", lot, limit_price, take_price, offset, units, spread, byMarket, limit_stop_price);
                    }
                }
            }

            mainWindow._dataProvider.StopLossOrderList.Add(new StopOrderModel()
            {
                TID = tid,
                Seccode = deal.Seccode,
                TradeAccount = deal.Account,
                ClientCode = deal.ClientCode,
                StopPrice = take_price,
                Price = limit_stop_price,
                OtsupMaxMin = offset,
                Spread = spread,
                TypeStop = cfg.StopTakeOrder,
                Count = lot,
                Status = null
            });
        }

        #endregion

        /// <summary>
        /// Поиск кода класса по кода бумаги
        /// </summary>
        /// <param name="_seccode">Код Бумаги</param>
        /// <returns>Возвращает код Класса по коду Бумаги</returns>
        private string GetClasscode(string _seccode)
        {
            for (int i = 0; i < mainWindow._dataProvider.CurrentList.Count; i++)
                if (mainWindow._dataProvider.CurrentList[i].Seccode == _seccode)
                    return mainWindow._dataProvider.CurrentList[i].ClassCode;

            return "";
        }

        /// <summary>
        /// Поиск последней сделки
        /// </summary>
        /// <param name="list"> массив сделок</param>
        /// <returns>Возвращает последнюю сделку</returns>
        private DealModel Search(List<DealModel> list, List<DealModel> lastdeal)
        {
            DealModel result = new DealModel();

            String operation = "";
            if (positionModel.Count > 0) operation = cfg.Buy;
            if (positionModel.Count < 0) operation = cfg.Sell;

            for (int i = list.Count - 1; i >= 0; i--)
            {
                if (list[i].Seccode == positionModel.Seccode && positionModel.Account == list[i].Account && positionModel.ClientCode == list[i].ClientCode)
                    if (list[i].Operation == operation)
                    {
                        result = list[i];

                        bool tr = false;
                        for (int j = 0; j < lastdeal.Count; j++)
                        {
                            if (lastdeal[j].Seccode == result.Seccode)
                                if (lastdeal[j] != result)
                                {
                                    lastdeal[j] = result;
                                    tr = true;
                                }
                        }
                        if (tr == false)
                            lastdeal.Add(result);

                        return result;
                    }
            }
            return result;
        }

        /// <summary>
        /// Лист стопов по коду бумаги
        /// </summary>
        /// <param name="seccode">код бумаги</param>
        /// <returns>Лист стопов по коду бумаги seccode</returns>
        private List<StopListModel> GetStops(PositionModel pm)
        {
            List<StopListModel> result = new List<StopListModel>();
            result = mainWindow._dataProvider.StopList.
                Where(a => a.Seccode == pm.Seccode).
                Where(a => a.Account == pm.Account).
                Where(a => a.ClientCode == pm.ClientCode && a.IsStart == true).ToList();
            return result;
        }

        /// <summary>
        /// Определение расчитывать цену заявки или в процентах или в валюте депозита
        /// </summary>
        /// <param name="p">тип расчета который выбран в таблице</param>
        /// <returns>строка типа расчета для использования в транзакции</returns>
        private string GetTypeR(string p)
        {
            if (p == cfg.ValutPrice)
                return "PRICE_UNITS";
            if (p == cfg.Persent)
                return "PERCENTS";

            return null;
        }

        /// <summary>
        /// Возвращает заявку по номеру
        /// </summary>
        /// <param name="number"></param>
        /// <returns></returns>
        private OrderModel GetOrder(long number)
        {
            OrderModel result = new OrderModel();

            for (int i = 0; i < mainWindow._dataProvider.OrderList.Count; i++)
            {
                if (mainWindow._dataProvider.OrderList[i].Number == number)
                    return mainWindow._dataProvider.OrderList[i];
            }

            return result;
        }
    }
}
